import VueRouter from "vue-router";
import routes from "./routes";
import Vue from "vue";
import store from "../store";
Vue.use(VueRouter);
const router = new VueRouter({
  routes,
  mode: "history",
});

router.beforeEach((to, from, next) => {
  // 每当导航切换时（包含刷新页面的第一次），该函数会运行
  // from：之前的路由对象  (this.$route)
  // to: 即将进入的路由对象 (this.$route)
  // next: 确认导航的一个函数  调用该函数（无参），就会直接进入to， 调用该函数（传入参数），根据传入参数进入新的导航
  if (to.meta.auth) {
    const statue = store.getters["loginUrl/statue"];
    const user = store.state.loginUrl.user;
    console.log(user, to.fullPath);
    if (to.fullPath === "/login" && user) {
      alert("当前用户已登录");
      next({
        path: "/",
      });
    } else {
      if (statue === "loading") {
        next({
          path: "/loading",
          query: {
            returnUrl: to.fullPath,
          },
        });
      } else if (statue === "login") {
        next();
      } else {
        alert("该页面需要登陆");
        next({
          path: "/login",
          query: {
            returnUrl: to.fullPath,
          },
        });
      }
    }
  } else {
    next();
  }
});

export default router;
